<template>
  <div>
    <el-form label-width="100px" :model="spuInfo">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select value="" placeholder="请选择品牌" v-model="spuInfo.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="(tm, index) in trademarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="SPU描述"
          rows="4"
          v-model="spuInfo.description"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :file-list="spuImageList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-select
          :placeholder="
            unUsedSaleAttrList.length
              ? `还有${unUsedSaleAttrList.length}未选择`
              : '没有了'
          "
          v-model="unUsedSaleAttrIdName"
        >
          <el-option
            :label="unUsedSaleAttr.name"
            :value="`${unUsedSaleAttr.id}:${unUsedSaleAttr.name}`"
            v-for="(unUsedSaleAttr, index) in unUsedSaleAttrList"
            :key="unUsedSaleAttr.id"
          ></el-option>
        </el-select>

        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addSaleAttr"
          :disabled="!unUsedSaleAttrIdName"
          >添加销售属性</el-button
        >

        <el-table border style="width: 100%" :data="spuInfo.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="150">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                closable
                :disable-transitions="false"
                v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
                :key="saleAttrValue.id"
              >
                {{ saleAttrValue.saleAttrValueName }}
              </el-tag>
              <!-- @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm" -->
              <el-input
                v-model="row.saleAttrValueName"
                v-if="row.isEdit"
                class="input-new-tag"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`确定删除${row.saleAttrName}吗？`"
                @onConfirm="spuInfo.spuSaleAttrList.splice($index, 1)"
              >
                <HintButton
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  title="删除"
                  size="mini"
                ></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancleBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      unUsedSaleAttrIdName: "",
      category3Id: "",
      dialogImageUrl: "",
      dialogVisible: false,
      //指定的一个商品的详细的sup信息
      spuInfo: {
        category3Id: "",
        spuName: "",
        description: "",
        tmId: "",
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      },
      //指定的一个商品的sup的图片列表
      spuImageList: [],
      // 所有品牌列表
      trademarkList: [],
      //所有销售属性
      baseSaleAttrList: [],
    };
  },
  methods: {
    //删除一张图片就会在这个函数当中收集最新的图片列表
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.spuImageList = fileList;
    },
    //预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //添加收集最新图片
    handleSuccess(res, file, fileList) {
      // console.log(res);
      // console.log(file);
      // console.log(fileList);
      this.spuImageList = fileList;
    },

    // 点击父组件添加触发
    async getInitAddSpuFormData(category3Id) {
      this.category3Id = category3Id;
      // http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      //获取所有的品牌列表
      const result2 = await this.$API.trademark.getList();
      if (result2.code === 20000 || result2.code === 200) {
        this.trademarkList = result2.data;
      }

      // http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      // 获取所有的销售属性列表
      const result3 = await this.$API.spu.getSaleAttrList();
      if (result3.code === 20000 || result3.code === 200) {
        this.baseSaleAttrList = result3.data;
      }
    },

    //父组件点击修改触发
    async getInitUpdateSpuFormData(spu, category3Id) {
      this.category3Id = category3Id;
      // http://localhost:9529/dev-api/admin/product/getSpuById/1295

      //拿到 spuInfo: 包含一个spu详细信息的对象，信息比较详细的
      const result = await this.$API.spu.get(spu.id);
      if (result.code === 20000 || result.code === 200) {
        this.spuInfo = result.data;
      }

      // http://localhost:9529/dev-api/admin/product/spuImageList/1295

      // 拿到获取指定SPU的id对应的图片列表
      const result1 = await this.$API.sku.getSpuImageList(spu.id);
      if (result1.code === 20000 || result1.code === 200) {
        const spuImageList = result1.data;
        spuImageList.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = spuImageList;
      }

      // http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      //获取所有的品牌列表
      const result2 = await this.$API.trademark.getList();
      if (result2.code === 20000 || result2.code === 200) {
        this.trademarkList = result2.data;
      }

      // http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      // 获取所有的销售属性列表
      const result3 = await this.$API.spu.getSaleAttrList();
      if (result3.code === 20000 || result3.code === 200) {
        this.baseSaleAttrList = result3.data;
      }
    },

    //           {
    //         				baseSaleAttrId: 0,
    //         				saleAttrName: "string",
    //         				spuSaleAttrValueList: [],
    //       			}
    // 点击添加销售属性
    addSaleAttr() {
      //把收集的数据变为一个对象
      let [baseSaleAttrId, saleAttrName] = this.unUsedSaleAttrIdName.split(":");
      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      // 2.把对象添加到指定的数组当中
      this.spuInfo.spuSaleAttrList.push(obj);
      //3.清空选中项
      this.unUsedSaleAttrIdName = "";
    },
    //点击添加按钮（添加属性值按钮）
    showInput(row) {
      this.$set(row, "isEdit", true);
      this.$set(row, "saleAttrValueName", "");

      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    //用户输入完数据之后回车或者失去焦点
    handleInputConfirm(row) {
      let { baseSaleAttrId, saleAttrValueName } = row;
      //属性值名称不能为空
      if (!saleAttrValueName.trim()) {
        // this.$message.error("属性值名称不能为空");
        row.saleAttrValueName = "";
        row.isEdit = false;
        return;
      }
      //属性值名称不能重复
      const isRepeat = row.spuSaleAttrValueList.some((item) => {
        return item.saleAttrValueName === saleAttrValueName;
      });
      if (isRepeat) {
        row.saleAttrValueName = "";
        row.isEdit = false;
        this.$message.error("属性值名称不能重复");
        return;
      }

      let obj = { baseSaleAttrId, saleAttrValueName };
      row.spuSaleAttrValueList.push(obj);
      row.saleAttrValueName = "";
      row.isEdit = false;
    },
    //点击保存
    async save() {
      //收集参数
      let { category3Id, spuInfo, spuImageList } = this;
      //整理参数

      // 获取category3Id
      spuInfo.category3Id = category3Id;
      //清除supInfo中多余属性
      spuInfo.spuSaleAttrList.forEach((item) => {
        delete item.isEdit;
        delete item.saleAttrValueName;
      });
      //spuImageList图片整理
      spuInfo.spuImageList = spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data,
        };
      });

      // 发请求
      try {
        const result = await this.$API.spu.addUpdate(spuInfo);
        if (result.code === 20000 || result.code === 200) {
          this.$message.success("保存spu成功");
          this.$emit("update:isShowSpuForm", false);
          this.$emit("successBack", spuInfo.id);
          this.resetData();
        } else {
          this.$message.success("保存spu失败");
        }
      } catch (error) {
        this.$message.error("请求保存spu失败");
      }
    },
    // 清空数据
    resetData() {
      Object.assign(this._data, this.$options.data());
    },
    //取消操作
    cancleBack() {
      this.$emit("update:isShowSpuForm", false);
      this.resetData();
    },
  },
  computed: {
    unUsedSaleAttrList() {
      return this.baseSaleAttrList.filter((item) => {
        return this.spuInfo.spuSaleAttrList.every((item1) => {
          return item.name !== item1.saleAttrName;
        });
      });
    },
  },
};
</script>

<style >
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>